package com.css.config.netty.message;

import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

public abstract class ByteBufBean {
	private Logger logger = LoggerFactory.getLogger(ByteBufBean.class);

	abstract public void writeBody(ByteBuf buf);

	abstract public void readBody(ByteBuf buf);

	protected String readUTF8(ByteBuf buf){
		int strSize = buf.readInt();
		byte[] content = new byte[strSize];
		buf.readBytes(content);
		try {
			return new String(content,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("读取数据失败", e);
			return "";
		}

	}

	protected  void writeUTF8(ByteBuf buf, String msg){
		byte[] content ;
		try {
			if (msg == null) {
				msg = "";
			}
			content = msg.getBytes("UTF-8");
			buf.writeInt(content.length);
			buf.writeBytes(content);
		} catch (UnsupportedEncodingException e) {
			logger.error("写数据失败", e);
		}
	}

}
